#!/usr/bin/env python

import traceback
import unittest
import test
import sys
import inspect
import time

# Class under test
from amsoftopenid.issohelpers import IssoHelpers

#Data objects
from amsoftopenid.dataobject import *

# Python imports

#Import Iservices specific Exception classes
from amsoftopenid.exception import IservicesException
from amsoftopenid.exception import IservicesSysException

from amsoftopenid.errcode import *
from amsoftopenid.constants import *
from amsoftopenid.properties import Properties

class TestIssoHelpers(unittest.TestCase):
    
    validGinu = "!!10099"
    inactiveGinu = "!!10098"
    invalidGinu = "10101"
    validIBrokerName = "localhost"
    expiredIBroker = "local_inactive"
    invalidIBrokerName = "invalidIBroker"
    validGreeting = "iLwhCDlnYX81"
    validSessionCookie = "8B2e1XawUWTwJLxNmDoz6GYFEN4="
    validMachineCookie = "xM/J7+zjuY5C+6Q2Ynbq1oNypSM="

    invalidSessionCookie = "invalidSession"
    invalidMachineCookie = "invalidMachine"
    
    sessionCookieExpired = "ESCsj1QeHVjCBoNGk043ZVp8FjM="
    machineCookieExpired = "HRtmZmZMfcy6lHZeXgPfVDJXxTc="
    expiredCookieId = 195
    
    def setUp(self):
       # get the db connection to be used throughout test
       pass
  
    #Private method to get DB connection
    def __getDBConn():
        #get absolute file path
        sPath = inspect.getfile(sys._getframe(1))
        iLen = sPath.index ('\openid') + 7
        sPath=sPath[0:iLen]
        sPath = sPath + '\util\db.properties'
        
        oProp = Properties()
        oProp.load(open(sPath))
        
        try:
            dbpool = DBConnectionPool(p['host'], p['user_name'], p['password'],
            p['database'], p['maxConnection'], 5, p['waitTime']).getTheInstance()
            dbConnection = dbpool.getConnection()
        except:
            raise IservicesException(NO_DATABASE_CONNECTION,
                                    dUtilErrorCodeMap[NO_DATABASE_CONNECTION])
        
        return dbConnection
    
    
    def tearDown(self):
        #test.cleanDB()
        pass

    """
        Test cases for testing fetchCookie() sESSION
    """
    def testFetchCookieSessionValid(self):
        oCookie = IssoHelpers.fetchCookie(self.validSessionCookie, COOKIE_TYPE_SESSION)
        self.failIfEqual(oCookie, None, "No Cookie exist")
        self.assertEqual(oCookie.getState(), COOKIE_STATE_ACTIVE,
                         "Cookie fetched is not active")
        self.assertEqual(oCookie.getType(), COOKIE_TYPE_SESSION,
                         "Cookie expected of Session type, is not")
    
    def testFetchCookieSessionInValid(self):
        oCookie = IssoHelpers.fetchCookie(self.invalidSessionCookie, COOKIE_TYPE_SESSION)
        self.assertEqual(oCookie, None,
                            "Expected None, returned a valid cookie obj")

    def testFetchCookieSessionExpired(self):
        try:
            IssoHelpers.fetchCookie(self.sessionCookieExpired, COOKIE_TYPE_SESSION)
        except IservicesException:
            oEx = sys.exc_info()[1]
            self.assertEqual(oEx.getCode(), SESSION_INVALID,
                             "Incorrect exception code. Expected 2009")
        except:
            oEx = sys.exc_info()[1]
            self.assertEqual(IservicesException, oEx, "Incorrect exception thrown")
        
    
    def testFetchCookieSessionForNone(self):
        try:
            IssoHelpers.fetchCookie(None, COOKIE_TYPE_SESSION)
        except IservicesException:
            oEx = sys.exc_info()[1]
            self.assertEqual(oEx.getCode(), INSUFFICENT_DATA,
                             "Incorrect exception code. Expected 2028")
        except:
            oEx = sys.exc_info()[1]
            self.assertEqual(IservicesException, oEx, "Incorrect exception thrown")
    
    def testFetchCookieSessionInvalidType(self):
        oCookie = IssoHelpers.fetchCookie(self.validSessionCookie, 3)
        self.assertEqual(oCookie, None,
                            "Expected None, returned a valid cookie obj")
    
    def testFetchCookieSessionNoneType(self):
        try:
            IssoHelpers.fetchCookie(self.validSessionCookie, None)
        except IservicesException:
            oEx = sys.exc_info()[1]
            self.assertEqual(oEx.getCode(), INSUFFICENT_DATA,
                             "Incorrect exception code. Expected 2028")
        except:
            oEx = sys.exc_info()[1]
            self.assertEqual(IservicesException, oEx, "Incorrect exception thrown")

    """
        Test cases for testing fetchPrincipal() MACHINE
    """
    def testFetchCookieMachineValid(self):
        oCookie = IssoHelpers.fetchCookie(self.validMachineCookie, COOKIE_TYPE_MACHINE)
        self.failIfEqual(oCookie, None, "No Cookie exist")
        self.failIfEqual(oCookie.getId(), None, "ID is not returned")
        self.assertEqual(oCookie.getState(), COOKIE_STATE_ACTIVE,
                         "Cookie fetched is not active")
        self.assertEqual(oCookie.getType(), COOKIE_TYPE_MACHINE,
                         "Cookie expected of Machine type, is not")
    
    def testFetchCookieMachineInValid(self):
        oCookie = IssoHelpers.fetchCookie("INVALID", COOKIE_TYPE_MACHINE)
        self.assertEqual(oCookie, None,
                            "Expected None, returned a valid cookie obj")

    def testFetchCookieMachineExpired(self):
        try:
            IssoHelpers.fetchCookie(self.machineCookieExpired, COOKIE_TYPE_MACHINE)
        except IservicesException:
            oEx = sys.exc_info()[1]
            self.assertEqual(oEx.getCode(), SESSION_INVALID,
                             "Incorrect exception code. Expected 2009")
        except:
            oEx = sys.exc_info()[1]
            self.assertEqual(IservicesException, oEx, "Incorrect exception thrown") 
    
    def testFetchCookieMachineForNone(self):
        try:
            IssoHelpers.fetchCookie(None, COOKIE_TYPE_MACHINE)
        except IservicesException:
            oEx = sys.exc_info()[1]
            self.assertEqual(oEx.getCode(), INSUFFICENT_DATA,
                             "Incorrect exception code. Expected 2028")
        except:
            oEx = sys.exc_info()[1]
            self.assertEqual(IservicesException, oEx, "Incorrect exception thrown")
    
    def testFetchCookieMachineInvalidType(self):
        oCookie = IssoHelpers.fetchCookie(self.validMachineCookie, 3)
        self.assertEqual(oCookie, None,
                            "Expected None, returned a valid cookie obj")
        
    def testFetchCookieMachineNoneType(self):
        try:
            IssoHelpers.fetchCookie(self.validMachineCookie, None)
        except IservicesException:
            oEx = sys.exc_info()[1]
            self.assertEqual(oEx.getCode(), INSUFFICENT_DATA,
                             "Incorrect exception code. Expected 2028")
        except:
            oEx = sys.exc_info()[1]
            self.assertEqual(IservicesException, oEx, "Incorrect exception thrown")
    
    """
        Test cases for testing fetchPrincipal()
    """
    def testFetchPrincipalForValid(self):
        oPrincipal = IssoHelpers.fetchPrincipal(self.validGinu)
        self.failIfEqual(oPrincipal, None, "No Principal exist, expected one")
        self.assertEqual(oPrincipal.getState(), PRINCIPAL_STATE_ACTIVE,
                         "Inactive principal returned")

    def testFetchPrincipalForInValid(self):
        oPrincipal = IssoHelpers.fetchPrincipal("Invalid")
        self.assertEqual(oPrincipal, None,
                         "Principal obj returned for invalid data. Expected None")
    
    def testFetchPrincipalForExpired(self):
        try:
            oPrincipal = IssoHelpers.fetchPrincipal(self.inactiveGinu)
        except IservicesException:
            oEx = sys.exc_info()[1]
            self.assertEqual(oEx.getCode(), ACCOUNT_INACTIVE,
                             "Incorrect exception code. Expected 2007")
        except:
            oEx = sys.exc_info()[1]
            self.assertEqual(IservicesException, oEx, "Incorrect exception thrown") 
            
        
    
    def testFetchPrincipalForNone(self):
        try:
            oPrincipal = IssoHelpers.fetchPrincipal(None)
        except IservicesException:
            oEx = sys.exc_info()[1]
            self.assertEqual(oEx.getCode(), INSUFFICENT_DATA,
                             "Incorrect exception code. Expected 2028")
        except:
            oEx = sys.exc_info()[1]
            self.assertEqual(IservicesException, oEx, "Incorrect exception thrown") 
               

    """
        Test cases for testing fetchIBroker()
    """
    def testFetchIBrokerForValid(self):
        oIBroker = IssoHelpers.fetchIBroker(self.validIBrokerName)
        self.assertNotEqual(oIBroker, None,
                         "None returned for valid broker name. Expected one")
        self.assertEqual(oIBroker.getState(), IBROKER_STATE_ACTIVE,
                         "Inactive broker returned")

    def testFetchIBrokerForInValid(self):
        oIBroker = IssoHelpers.fetchIBroker("Invalid")
        self.assertEqual(oIBroker, None,
                         "Broker obj returned for invalid data. Expected None")
    
    def testFetchIBrokerForExpired(self):
        oIBroker = IssoHelpers.fetchIBroker(self.expiredIBroker)
        self.assertEqual(oIBroker, None,
                         "Broker obj returned for expired broker. Expected None")
    
    def testFetchIBrokerForNone(self):
        try:
            oIBroker = IssoHelpers.fetchIBroker(None)
        except IservicesException:
            oEx = sys.exc_info()[1]
            self.assertEqual(oEx.getCode(), INSUFFICENT_DATA,
                             "Incorrect exception code. Expected 2028")
        except:
            oEx = sys.exc_info()[1]
            self.assertEqual(IservicesException, oEx, "Incorrect exception thrown")

    
    """
        Test cases for getPersonalizedGreeting()
    """
    def testGetPersonalizedGreetingForValid(self):
        sGreeting = IssoHelpers.getPersonalizedGreeting(self.validGinu)
        self.assertNotEqual(sGreeting, None,
                            "No greeting returned for valid GINU")
        self.assertEqual(sGreeting, self.validGreeting,
                            "Greeting value returned does not match expected value")

    def testGetPersonalizedGreetingForInValid(self):
        sGreeting = IssoHelpers.getPersonalizedGreeting("INVALID")
        self.assertEqual(sGreeting, None,
                            "Greeting returned for invalid GINU")
    
    def testGetPersonalizedGreetingForExpired(self):
        sGreeting = IssoHelpers.getPersonalizedGreeting(self.inactiveGinu)
        self.assertEqual(sGreeting, None,
                            "Greeting returned for expired principal. Expected None")
    
    def testGetPersonalizedGreetingForNone(self):
        try:
            sGreeting = IssoHelpers.getPersonalizedGreeting(None)
        except IservicesException:  
            oEx = sys.exc_info()[1]
            self.assertEqual(oEx.getCode(), INSUFFICENT_DATA,
                             "Incorrect exception code. Expected 2028")
        except:
            oEx = sys.exc_info()[1]
            self.assertEqual(IservicesException, oEx, "Incorrect exception thrown") 

    """
        Test cases for updateCookie()
    """
    def testUpdateCookieForValid(self):
        #Update mod time
        oCookie = IssoHelpers.fetchCookie(self.validSessionCookie, COOKIE_TYPE_SESSION)
        sCookieModificationTime = oCookie.getModificationTime()
        lCookieModificationTime = time.mktime(sCookieModificationTime.timetuple())
        
        time.sleep(2)
        try:
            IssoHelpers.updateCookie(oCookie.getId())
            
            #Fetch cookie to test
            oCookie = IssoHelpers.fetchCookie(self.validSessionCookie, COOKIE_TYPE_SESSION)
            sCookieModificationTimeNew = oCookie.getModificationTime()
            lCookieModificationTimeNew = time.mktime(
                sCookieModificationTimeNew.timetuple())
            self.failIfEqual(lCookieModificationTime, lCookieModificationTimeNew)
        except:
            oEx = sys.exc_info()[1]
            self.assertEqual(IservicesException, oEx, "Incorrect exception thrown")

    def testUpdateCookieForInValid(self):
        iInvalidId = -1
        try:
            IssoHelpers.updateCookie(iInvalidId)
            self.fail("Expected exception")
        except:
            oEx = sys.exc_info()[1]
            self.assertNotEqual(IservicesException, oEx)

    def testUpdateCookieForNone(self):
        try:
            IssoHelpers.updateCookie(None)
            self.fail("Expected exception")
        except IservicesException:  
            oEx = sys.exc_info()[1]
            self.assertEqual(oEx.getCode(), INSUFFICENT_DATA,
                             "Incorrect exception code. Expected 2028")
        except:
            oEx = sys.exc_info()[1]
            self.assertEqual(IservicesException, oEx, "Incorrect exception thrown")
    
    def testUpdateCookieForExpired(self):
        try:
            IssoHelpers.updateCookie(self.expiredCookieId)
        except:
            oEx = sys.exc_info()[1]
            self.fail("Unexpected exception=" + str(oEx)) 

    
    """
        Test cases for deleteCookie()
    """
    def testSessionDeleteCookieForValid(self):
        sCookie = str(time.time())
        try:
            IssoHelpers.createCookie(sCookie, self.validGinu, COOKIE_TYPE_SESSION)
            IssoHelpers.deleteCookie(sCookie, COOKIE_TYPE_SESSION)
            oCookie = IssoHelpers.fetchCookie(sCookie, COOKIE_TYPE_SESSION)
        except IservicesException:  
            oEx = sys.exc_info()[1]
            self.assertEqual(oEx.getCode(), SESSION_INVALID,
                             "Incorrect exception code. Expected 2009")
        except:
            oEx = sys.exc_info()[1]
            self.fail("Unexpected exception=" + str(oEx))         

    def testSessionDeleteCookieForInValid(self):
        try:
            IssoHelpers.deleteCookie("INVALID", COOKIE_TYPE_SESSION)
        except:
            oEx = sys.exc_info()[1]
            self.fail("Unexpected exception=" + str(oEx))

    def testSessionDeleteCookieForNone(self):
        try:
            IssoHelpers.deleteCookie(None, COOKIE_TYPE_SESSION)
        except IservicesException:  
            oEx = sys.exc_info()[1]
            self.assertEqual(oEx.getCode(), INSUFFICENT_DATA,
                             "Incorrect exception code. Expected 2028")
        except:
            oEx = sys.exc_info()[1]
            self.assertEqual(IservicesException, oEx, "Incorrect exception thrown")
 
    def testSessionDeleteCookieForExpired(self):
        try:
            IssoHelpers.deleteCookie(self.sessionCookieExpired, COOKIE_TYPE_SESSION)
        except:
            oEx = sys.exc_info()[1]
            self.fail("Unexpected exception=" + str(oEx))

    def testMachineDeleteCookieForValid(self):
        sCookie = str(time.time())
        try:
            IssoHelpers.createCookie(sCookie, self.validGinu, COOKIE_TYPE_MACHINE)
            IssoHelpers.deleteCookie(sCookie, COOKIE_TYPE_MACHINE)
            oCookie = IssoHelpers.fetchCookie(sCookie, COOKIE_TYPE_MACHINE)
        except IservicesException:  
            oEx = sys.exc_info()[1]
            self.assertEqual(oEx.getCode(), SESSION_INVALID,
                             "Incorrect exception code. Expected 2009")
        except:
            oEx = sys.exc_info()[1]
            self.fail("Unexpected exception=" + str(oEx))         

    def testMachineDeleteCookieForInValid(self):
        try:
            IssoHelpers.deleteCookie("INVALID", COOKIE_TYPE_MACHINE)
        except:
            oEx = sys.exc_info()[1]
            self.fail("Unexpected exception=" + str(oEx))

    def testMachineDeleteCookieForNone(self):
        try:
            IssoHelpers.deleteCookie(None, COOKIE_TYPE_MACHINE)
        except IservicesException:  
            oEx = sys.exc_info()[1]
            self.assertEqual(oEx.getCode(), INSUFFICENT_DATA,
                             "Incorrect exception code. Expected 2028")
        except:
            oEx = sys.exc_info()[1]
            self.assertEqual(IservicesException, oEx, "Incorrect exception thrown")
 
    def testMachineDeleteCookieForExpired(self):
        try:
            IssoHelpers.deleteCookie(self.machineCookieExpired, COOKIE_TYPE_MACHINE)
        except:
            oEx = sys.exc_info()[1]
            self.fail("Unexpected exception=" + str(oEx))

    def testSessionDeleteCookieInvalidType(self):
        iInvalid = -1
        try:
            IssoHelpers.deleteCookie(self.machineCookieExpired, iInvalid)
        except:
            oEx = sys.exc_info()[1]
            self.fail("Unexpected exception=" + str(oEx))
    
    """
        Test cases for createCookie()
    """
    def testSessionCreateCookieForValid(self):
        sCookie = str(time.time())
        try:
            IssoHelpers.createCookie(sCookie, self.validGinu, COOKIE_TYPE_SESSION)
            oCookie = IssoHelpers.fetchCookie(sCookie, COOKIE_TYPE_SESSION)
            self.assertNotEqual(oCookie, None, "Cookie didnt got created")
        except:
            oEx = sys.exc_info()[1]
            self.fail("Unexpected exception=" + str(oEx))
    
    def testSessionCreateCookieForNone(self):
        try:
            IssoHelpers.createCookie(None, self.validGinu, COOKIE_TYPE_SESSION)
            self.fail("Insufficenta Data Exception expected")
        except IservicesException:  
            oEx = sys.exc_info()[1]
            self.assertEqual(oEx.getCode(), INSUFFICENT_DATA,
                             "Incorrect exception code. Expected 2028")
        except:
            oEx = sys.exc_info()[1]
            self.assertEqual(IservicesException, oEx, "Incorrect exception thrown")

    def testSessionCreateCookieForNoneGINU(self):
        sCookie = str(time.time())
        try:
            IssoHelpers.createCookie(sCookie, None, COOKIE_TYPE_SESSION)
            self.fail("Insufficenta Data Exception expected")
        except IservicesException:  
            oEx = sys.exc_info()[1]
            self.assertEqual(oEx.getCode(), INSUFFICENT_DATA,
                             "Incorrect exception code. Expected 2028")
        except:
            oEx = sys.exc_info()[1]
            self.assertEqual(IservicesException, oEx, "Incorrect exception thrown")

    def testMachineCreateCookieForValid(self):
        sCookie = str(time.time())
        try:
            IssoHelpers.createCookie(sCookie, self.validGinu, COOKIE_TYPE_MACHINE)
            oCookie = IssoHelpers.fetchCookie(sCookie, COOKIE_TYPE_MACHINE)
            self.assertNotEqual(oCookie, None, "Cookie didnt got created")
        except:
            oEx = sys.exc_info()[1]
            self.fail("Unexpected exception=" + str(oEx))
    
    def testMachineCreateCookieForNone(self):
        try:
            IssoHelpers.createCookie(None, self.validGinu, COOKIE_TYPE_MACHINE)
            self.fail("Insufficenta Data Exception expected")
        except IservicesException:  
            oEx = sys.exc_info()[1]
            self.assertEqual(oEx.getCode(), INSUFFICENT_DATA,
                             "Incorrect exception code. Expected 2028")
        except:
            oEx = sys.exc_info()[1]
            self.assertEqual(IservicesException, oEx, "Incorrect exception thrown")

    def testMachineCreateCookieForNoneGINU(self):
        sCookie = str(time.time())
        try:
            IssoHelpers.createCookie(sCookie, None, COOKIE_TYPE_MACHINE)
            self.fail("Insufficenta Data Exception expected")
        except IservicesException:  
            oEx = sys.exc_info()[1]
            self.assertEqual(oEx.getCode(), INSUFFICENT_DATA,
                             "Incorrect exception code. Expected 2028")
        except:
            oEx = sys.exc_info()[1]
            self.assertEqual(IservicesException, oEx, "Incorrect exception thrown")
    
def main():
    unittest.main()

if __name__ == '__main__':
    main()
    
    